package com.shiro.work1.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shiro.work1.domain.Album;

import com.shiro.work1.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

@Service
@Slf4j
public class MusicService {
    @Value("classpath:/music.json")
    private Resource musicData;

    public String selectById(){
        String musicJson="";
        try {
            musicJson = IOUtils.toString(musicData.getInputStream(), Charset.forName("UTF-8"));
        } catch (IOException e) {
            log.error("",e);
        }
        //获取全部歌曲map集合
        List<HashMap<String, Object>> songList = JsonUtils.getAlbum(musicJson);
        //创建set集合去重
        TreeSet<Album> albums = new TreeSet<>();
        //创建map存入最后归类的map集合,以专辑id为key，以所有歌曲的名字为value
        HashMap<Long, List<String>> realSongs = new HashMap<>();
        for (HashMap<String, Object> songMap : songList) {
            Album album = new Album();
            Long id = Long.parseLong((String)songMap.get("id"));
            String author = (String) songMap.get("author");
            String name = (String)songMap.get("name");
            String song = (String)songMap.get("song");
            album.setId(id);
            album.setAuthor(author);
            album.setName(name);
            albums.add(album);
            //歌曲需要判断
            ArrayList<String> ss = new ArrayList<>();
            //存在id，先获取key对应的value再添加
            if(realSongs.containsKey(id)){
                ss= (ArrayList<String>) realSongs.get(id);
            }
            //不存在添加
            ss.add(song);
            //无论是否存在key，存在则覆盖，不存在则创建
            realSongs.put(id,ss);
        }
        for (Album album : albums) {
            List<String> songs = realSongs.get(album.getId());
            album.setSongs(songs);
        }

        return JSON.toJSONString(albums);
    }

}
